<template>
  <card-group-solt
  @handleClick="changeTab"
  :activeName="activeName"
  :tabPanes="tabPanes"
    :cardLoading="loading">
    <template  :slot="'search'">
      <search :type="activeName">
        <template :slot="'select'">
          <v-select :selectOptions="search[activeName].isChildren.select"
                    @quickSelect="handlerQuickSelect"
                    :form="search[activeName].currentSelect"
                    @show="selectShow"
                    :noChange="noChange">
          </v-select>
        </template>
        <template :slot="'inputSearch'">
          <input-search @quickSearch="nomalSearch" :placeHolder="search.placeHolder" :form="search[activeName].isChildren.nomalForm"></input-search>
        </template>
        <template :slot="'advancedSearch'">
          <advanced-search
            @ifRemark="ifRemark"
            v-if="search[activeName].isChildren.adv"
            :adv="search[activeName].isChildren.adv"
            :badge="search[activeName].isChildren.adv.badgeList"
            :formItemsConfig="formItemsConfigs && formItemsConfigs[activeName]"
            :activeName="activeName"
            @selectChange="handlerSelectChange"
            @advSearch="advSearch"
            @resetForm="resetAdvSearch"
            @confirmNewItemsConfig="handleConfirmNewItemsConfig"
          ></advanced-search>
        </template>
        <template :slot="'changeCardStyle'">
          <div  @click="changeToNewBusiness" style="position:absolute;top:10px;right:40px;cursor:pointer;">
            <i class='iconfont icon-qiehuanshitu'></i>
            <div v-if='!getNoviceKeyStatus.businessViewSwitch' style="position: absolute;top: -15px;right:7px ;padding-bottom: 10px;z-index: 100;cursor: default;">
            <popover-novice
              style="position: absolute;right: -25px;top: 15px;"
              noviceKey = 'businessViewSwitch'
              :noviceHtml = "{title: '', text: '视图切换功能：可根据个人习惯选择切换卡片视图，列表视图'}"
            @updateGuidanceSuccess="updateGuidanceSuccess('click')"
          ></popover-novice>
          </div>
         </div> 
        </template>
        <template :slot="'CustRefresh'">
          <refresh v-if="search[activeName].isChildren.refresh" @refresh="handleRefresh" :class="'positionClass'"></refresh>
        </template>
        <template :slot="'dropdownSelect'">
          <el-tooltip class="item" effect="dark" :content="$t('business.newBusiness')" placement="bottom">
            <i class="iconfont icon-gongdanxialacaidan" @click.stop="addNewBusiness" style="font-size: 18px;padding-right:4px;cursor:pointer;"></i>
          </el-tooltip>
          <el-dropdown class="rel-operation" trigger="click" @command="plus" size="small">
          <span class="el-dropdown-link">
             <el-tooltip class="item" effect="dark" :content="$t('public.moreOper')" placement="bottom">
               <i class=" iconfont icon-gengduo" style="font-size: 18px;display:inline-block;margin-top:1px;"></i>
             </el-tooltip>
          </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item class="ro-dropdown" command="/index/business/customSearch">{{$t('customer.CustomerSearch.CustomizeFastSearch')}}</el-dropdown-item>
              <el-dropdown-item class="ro-dropdown" command="/index/business/exportTask">{{' ' + $t('webchat.exportTaskList')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template :slot="'advSchBadge'">
          <advSchBadge :remark="search[activeName].partakeAgentRemark" v-if="search[activeName].isChildren.adv.badgeList" :badge="search[activeName].isChildren.adv.badgeList" @removeBadge="removeBadge"></advSchBadge>
        </template>
      </search>
    </template>
    <template slot="pagination"> 
      <pagination
        :customerShow="true"
        :small="search[activeName].pagination.small"
        :currentPage="search[activeName].pagination.currentPage"
        :count="count"
        :moreFlag="moreFlag"
        :allCount="allCount"
        :type="type"
        :later="laterProcessData.length>0"
        :tabType="activeName"
        @turnPage="turnPage"
        :totalPage="totalPage"
        @getAllCount="getAllCount"
      >
      </pagination>
    </template>
    <template :slot="'cardList'">
      <business-card
              :allCount="allCount"
              :count="count"
              :type="type"
              :qu="qu"
              :quAction="quAction"
              :tabType="activeName"
              @allCountClear="allCountClear"
              :condition = search[activeName].condition
              :clearChecked = "clearChecked"
              @changeCardItem="changeCardItem"
              :laterProcessData="laterProcessData"
      >
      </business-card>
    </template>
  </card-group-solt>
</template>
<script>
  const normalForm = {query: '', page: 1, morePage: 1, limit: 10}
  const businessAll = {status: null, createUser: null, ownercomCreateUser: null, ownerdepCreateUser: null, query: null, flow: [], step: null, processTimeout: '', processMember: null, ownercomProcessMember:null,ownerdepProcessMember:null,customField:null,textFieldContent:null,master: null, ownercom: null, ownerdep: null, number: null, createTime: null, priority: null, followedAgents: '', processEndTime: null, searchType: '', custom: {}, stepHistory: null}
  import CardGroupSolt from '@/components/public-modules/card/NewIndex' 
  import BusinessCard from './BusinessCard'
  import Search from '@/components/public-modules/card/search/NewIndex'
  import Select from '@/components/public-modules/card/search/Select'
  import InputSearch from '@/components/public-modules/card/search/InputSearch'
  import AdvancedSearch from '@/components/public-modules/card/search/Advanced2Search.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import Refresh from '../../ui-modules/icon/Refresh'
  import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge.vue'
  import {advancedSearchBack, getFlowStepNameByCache, getTextFieldsNameByCache,getStartStep, getFlowStepById, createFlowCustomFields, addBusienssSelectCascade} from '@/utils/workflowUtils'
  import {utilExtend, deepClone, getDateTime, removeEmptyProperty, getFormatDateTime} from '@/utils/m7Utils'
  import { changeActiveTab, changeActiveList } from '@/utils/shortcutKey'
  import popoverNovice from '@/components/public-modules/novice-boot/popoverNovice.vue'
import itemVue from '../km/km-search/item.vue'
  import { addZhuGeTrack } from '@/utils/addZhuGeTrack.js'
  export default {
    name: 'BusinessCardGroup',
    data () {
      let timeoutData = [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.totalTimeStateUncomplete2'), value: true}, {label: this.$t('business.noTimeout'), value: false}]
      let attachmentData = [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.attachment'), value: true}, {label: this.$t('business.noAttachment'), value: false}]
      let priorityData = [{label: this.$t('business.priority1'), value: '1__' + this.$t('business.priority1')}, {label: this.$t('business.priority2'), value: '2__!' + this.$t('business.priority2'), class: 'business-priority2'}, {label: this.$t('business.priority3'), value: '3__!!!' + this.$t('business.priority3'), class: 'business-priority3'}]
      //工单创建方式数据
      let createModeData = [{label: this.$t('business.sessionCreate'), value: 'webchat__' + this.$t('business.sessionCreate')}, {label: this.$t('business.callsCreate'), value: 'call__' + this.$t('business.callsCreate')}, {label: this.$t('business.businessCreation'), value: 'business__' + this.$t('business.businessCreation')}, {label: this.$t('business.interfaceCreate'), value: 'interface__' + this.$t('business.interfaceCreate')}, {label: this.$t('business.customerCreate'), value:'customer__' + this.$t('business.customerCreate')}, {label: this.$t('business.mailCreate'), value: 'email__' + this.$t('business.mailCreate')}]
//      let sessionId = this.$store.state.session.sessionId
      return {
        getNoviceKeyStatus: {'businessViewSwitch': false},
        allCount: 0,
        pages: 0,  //  pageMore  翻页优化相关
        qu: {},
        quAction: 'queryAllBusinessCount',
        loading: true,
        activeName: this.$route.params.tabType || 'business_undeal',
        type: 'business',
        clearChecked: 0,
        noChange: false,
        currentPage: null,
        search: {
          // isAdvSearch: false,
          isSearch: false, // 是否正在执行搜索
          advSearchCondition: {}, // 高级搜索的查询条件展示
          placeHolder: this.$t('business.queryPlaceHolding'),
          business_undeal: {
            currentSelect: {value: undefined, condition: {}},
            isAdvSearch: false,
            partakeAgentRemark: false,
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            condition: {},
            isChildren: {
              rel: false,
              refresh: true,
              select: [
              ],
              defaultSelect: '',
              nomal: true,
              nomalForm: deepClone(normalForm),
              adv: {
                form: {createUser: null, ownercomCreateUser: null, ownerdepCreateUser: null, flow: [], step: null, processTimeout: '', processMember: null,ownercomProcessMember:null,ownerdepProcessMember:null,customField:null,textFieldContent:null, number: null, createTime: null, priority: null, followedAgents: '', searchType: '', custom: {}, stepHistory:null},
                advSearchOptions: {
                  localed: [
                    {label: this.$t('business.searchScope'), name: 'searchType', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.myFollowedBusiness'), value: 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')}]},
                    {label: this.$t('public.creator'), name: 'createUser', inputType: 'owner'},
                    {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
                    {label: this.$t('business.businessFlow'), filterable: true, name: 'flow', inputType: 'select', data: [], multiple: true},
                    {label: this.$t('business.businessStep'), name: 'step', inputType: 'select', data: [],multiple: true},
                    {label: this.$t('business.businessNumber'), name: 'number', inputType: 'input', validateType: 'Number3'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'owner'},
                    {label: this.$t('business.workOrderFuzzySearchField'), name: 'customField', inputType: 'select', data: []},
                    {label: this.$t('business.fuzzySearchContent'), name: 'textFieldContent', inputType: 'input',disabled:true},
                    {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
                    {label: this.$t('business.priorityLabel'), name: 'priority',  inputType: 'select', data: priorityData, multiple: true},
                    {label: this.$t('business.businessAttachment'), name: 'existAttach', inputType: 'select', data: attachmentData},
                    {label: this.$t('business.businessCreationMode'), name: 'createMode', inputType: 'select', multiple: true, data: createModeData},
                    {label: this.$t('business.businessHistoryStep'), name: 'stepHistory', inputType: 'select', data: [],multiple: true}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          },
          business_my: {
            currentSelect: {value: undefined, condition: {}},
            isAdvSearch: false,
            partakeAgentRemark: false,
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            condition: {},
            isChildren: {
              rel: false,
              refresh: true,
              select: [
              ],
              defaultSelect: '',
              nomal: true,
              nomalForm: deepClone(normalForm),
              adv: {
                form: {createUser: null, ownercomCreateUser: null, ownerdepCreateUser: null, query: null, flow: [], step: null, processTimeout: '', processMember: null,ownercomProcessMember:null,ownerdepProcessMember:null, customField:null,textFieldContent:null,number: null, createTime: null, priority: null, followedAgents: '', searchType: '', custom: {},stepHistory:null},
                advSearchOptions: {
                  localed: [
                    {label: this.$t('business.searchScope'), name: 'searchType', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.myFollowedBusiness'), value: 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')}, {label: this.$t('business.myTemp'), value: 'temp__' + this.$t('business.myTemp')}]},
                    {label: this.$t('public.creator'), name: 'createUser', inputType: 'owner'},
                    {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
                    {label: this.$t('business.businessFlow'), filterable: true, name: 'flow', inputType: 'select', data: [], multiple: true},
                    {label: this.$t('business.businessStep'), name: 'step', inputType: 'select', data: [],multiple: true},
                    {label: this.$t('business.businessNumber'), name: 'number', inputType: 'input'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('business.priorityLabel'), name: 'priority', inputType: 'select', data: priorityData, multiple: true},
                    {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'owner'},
                    {label: this.$t('business.workOrderFuzzySearchField'), name: 'customField', inputType: 'select', data: []},
                    {label: this.$t('business.fuzzySearchContent'), name: 'textFieldContent', inputType: 'input',disabled:true},
                    {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
                    {label: this.$t('business.businessAttachment'), name: 'existAttach', inputType: 'select', data: attachmentData},
                    {label: this.$t('business.businessCreationMode'), name: 'createMode', inputType: 'select', multiple: true, data: createModeData},
                    {label: this.$t('business.businessHistoryStep'), name: 'stepHistory', inputType: 'select', data: [],multiple: true}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          },
          business_all: {
            currentSelect: {value: undefined, condition: {}},
            isAdvSearch: false,
            partakeAgentRemark: false,
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            condition: {},
            isChildren: {
              rel: true,
              refresh: true,
              quickSelectDefault: 'time__week',
              select: [],
              defaultSelect: 'time__week',
              nomal: true,
              nomalForm: deepClone(normalForm),
              adv: {
                form: deepClone(businessAll),
                advSearchOptions: {
                  localed: [
                    {label: this.$t('business.searchScope'), name: 'searchType', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('business.myFollowedBusiness'), value: 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')}, {label: this.$t('business.myParticipated'), value: 'myParticipated__' + this.$t('business.myParticipated')}, {label: this.$t('business.myTemp'), value: 'temp__' + this.$t('business.myTemp')}]},
                    {label: this.$t('business.businessStatus'), name: 'status', inputType: 'select', data: [{label: this.$t('business.undeal'), value: 'dealing__' + this.$t('business.undeal')},{label: this.$t('business.todo'), value: 'dealing__' + this.$t('business.todo')}, {label: this.$t('business.finished'), value: 'complete__' + this.$t('business.finished')}, {label: this.$t('public.cancel'), value: 'cancel__' + this.$t('public.cancel')}],multiple: true},
                    {label: this.$t('public.creator'), name: 'createUser', inputType: 'owner'},
                    {label: this.$t('business.customerName'), name: 'query', inputType: 'input'},
                    {label: this.$t('business.businessFlow'), filterable: true, name: 'flow', inputType: 'select', data: [], multiple: true},
                    {label: this.$t('business.businessStep'), name: 'step', inputType: 'select', data: [],multiple: true},
                    {label: this.$t('business.master'), name: 'master', inputType: 'owner'},
                    {label: this.$t('business.businessNumber'), name: 'number', inputType: 'input'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('business.processEndTime'), name: 'processEndTime', inputType: 'time'},
                    {label: this.$t('business.priorityLabel'), name: 'priority', inputType: 'select', data: priorityData, multiple: true},
                    {label: this.$t('business.partakeAgent'), name: 'processMember', inputType: 'owner'},
                    {label: this.$t('business.workOrderFuzzySearchField'), name: 'customField', inputType: 'select', data: []},
                    {label: this.$t('business.fuzzySearchContent'), name: 'textFieldContent', inputType: 'input',disabled:true},
                    {label: this.$t('business.overtimeBusiness'), name: 'processTimeout', inputType: 'select', data: timeoutData},
                    {label: this.$t('business.businessAttachment'), name: 'existAttach', inputType: 'select', data: attachmentData},
                    {label: this.$t('business.businessCreationMode'), name: 'createMode', inputType: 'select', multiple: true, data: createModeData},
                    {label: this.$t('business.businessHistoryStep'), name: 'stepHistory', inputType: 'select', data: [],multiple: true}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          }
        },
        formItemsConfigs: {},
        laterProcessData:[],
        nameArr:[]
      }
    },
    provide () {
      return {
        itemsDisabled: {
          business_all: {
            createTime: true
          }
        }
      }
    },
    beforeMount () {
      this.defaultSetting()
      Promise.all([this.$store.dispatch('getCache', {type: 'businessFlowField'}), this.$store.dispatch('getCache', {type: 'options'}), this.$store.dispatch('getCache', {type: 'custTmpls'})]).then(() => {
        getBusinessFlow(this.$store).then(() => {
          this.tabPanes.forEach((tabPane) => {
            this.search[tabPane.type].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'flow') {
                item.data = this.$store.state.business.transCache.businessTypes
              }
            })
          })
          this.refreshCustomSearch().then(() => {
            this.currentPage = true
            this.routeToMe(true)
          })
        })
      })
      this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
        let agent = res || []
        let data = [{label: this.$t('public.all'), value: ''}]
        let data2 = [{label: this.$t('public.all'), value: ''}]
        if (agent) {
          for (let i = 0; i < agent.length; i++) {
            if (agent[i]._id !== this.$store.state.session.sessionId) {
              data.push({label: agent[i].displayName, value: `${agent[i]._id}__${agent[i].displayName}`})
            }
            data2.push({label: agent[i].displayName, value: `${agent[i]._id}__${agent[i].displayName}`})
          }
        }
        let arr = ['business_undeal', 'business_my', 'business_all']
        arr.forEach((item) => {
          let nameType = item
          this.search[item].isChildren.adv.advSearchOptions.localed.forEach((item) => {
            if (item.name === 'processMember' && nameType === 'business_undeal') {
              item.data = data2
            } else if (item.name === 'processMember') {
              item.data = data
            }
          })
        })
      })
      this.$store.dispatch('getAdvSearchConfig', {searchType: 'BusinessCardGroup'}).then((config) => {
        this.formItemsConfigs = config || {}
      })
      this.updateGuidanceSuccess()
      console.log(this.search,999);
    },
    activated () {
      if (this.currentPage === null) {
        // 第一次进入组件时 currentPage未null 不执行routeToMe函数，在beforeMount里执行
        return
      }
      this.currentPage = true
      this.routeToMe()
    },
    deactivated () {
      this.currentPage = false
    },
    computed: {
      shortcutOpen: {
        get(){
          return this.$store.state.config.shortcutKey.openShortcutKey.commonSwitch
        },
        set(v) { }
      },
      noticeBusJump () {
        return this.$store.state.noticeBusJump.random
      },
      customSearch () {
        return this.$store.state.business.transCache.customSearch
      },
      // cardList () {
      //   return JSON.parse(JSON.stringify(this.$store.state[this.type][this.type + 'List'].list || []))
      // },
      moreFlag () {
        if (this.$store.state[this.type][this.type + 'List'].more) {
          return true
        } else {
          return false
        }
      },
      count () {
        return this.$store.state[this.type][this.type + 'List'].count
      },
      totalPage () {
        return Math.ceil(this.$store.state[this.type][this.type + 'List'].count / 10) || 0
      },
      refreshLeftcard () {
        return this.$store.state.business.transCache.refreshLeft
      },
      tabPanes () {
        let roleNum = this.$store.state.business.roleNum
        let total = this.$store.state.business.total
        let noReadNum = this.$store.state.business.noReadNum
        if (roleNum > 99) {
          roleNum = '99+'
        }
        if (total > 99) {
          total = '99+'
        }
        if (noReadNum > 99) {
          noReadNum = '99+'
        }
        return [
          {name: this.$t('business.undealBusiness') + roleNum, type: 'business_undeal'},
          {name: this.$t('business.myTodo') + noReadNum + '/' + total, type: 'business_my'},
          {name: this.$t('business.allBusiness'), type: 'business_all'}
        ]
      }
    },
    watch: {
      refreshLeftcard () {
        this.handleRefresh()
      },
      customSearch () {
        this.refreshCustomSearch()
      },
      noticeBusJump () {
        let data = this.$store.state.noticeBusJump
        if (data.module === 'business' && this.currentPage) {
          this.routeToMe()
        }
      },
      $route (to, from) {
        try {
          if (to.meta.title !== from.meta.title) {
            if (to.meta.title === 'business') {
              document.addEventListener('keydown', this.shortcutDispatch)
            } else {
              document.removeEventListener('keydown', this.shortcutDispatch)
            }
          }
        } catch(err) {
          console.log(err)
        }
      },
      shortcutOpen () {
        if(this.shortcutOpen) {
          document.addEventListener('keydown', this.shortcutDispatch)
        } else {
          document.removeEventListener('keydown', this.shortcutDispatch)
        }
      }
    },
    methods: {
      shortcutDispatch(e) {
        if (e.altKey && e.keyCode === 39) { //right
          changeActiveTab({
            el: this.$el,
            isIncrease: true
          })
        }
        if (e.altKey && e.keyCode === 37) { //left
          changeActiveTab({
            el: this.$el,
          })
        }
        const list = {  // tab横向切换class名,以及快捷键值
          boxClass: 'el-menu',
          activeClass: 'custom-is-active',
          itemClass: 'el-menu-item'
        }
        if (e.altKey && e.keyCode === 40) { // down
          changeActiveList({
            list,
            el: this.$el,
            isIncrease: true
          })
        }
        if (e.altKey && e.keyCode === 38) { // up
          changeActiveList({
            list,
            el: this.$el
          })
        }
      },
      changeToNewBusiness () {
        this.$store.commit('IS_NEW_CARD_STYLE', {type: 'business', data: true})
        this.$store.dispatch('updateViewSwitch', {module: 'business', status: 'new'})
      },
      // 快捷搜索下拉框打开
      selectShow () {
        if (this.activeName === 'business_my') {
          // 查询暂存工单和稍后处理工单数量
          let master = this.$store.state.session.sessionId
          let temp = this.$store.dispatch('queryAllBusinessCount', {queryCount: true, master, saveFlag: 'temp'})
          let laterProcess = this.$store.dispatch('queryAllBusinessCount', {queryCount: true, master, laterProcess: true})
          let back= this.$store.dispatch('queryAllBusinessCount',{queryCount:true,master,isBack:true})
          Promise.all([temp, laterProcess,back]).then(([tempNum, laterNum,backNum])=> {
            this.search.business_my.isChildren.select[1].label = this.$t('business.laterProcess') + `(${laterNum.count > 99 ? 99 + '+' : laterNum.count})`
            this.search.business_my.isChildren.select[2].label = this.$t('business.myTemp') + `(${tempNum.count > 99 ? 99 + '+' : tempNum.count})`
            this.search.business_my.isChildren.select[3].label = this.$t('business.backBusiness') + `(${backNum.count > 99 ? 99 + '+' : backNum.count})`

          })
        }
      },
      handleConfirmNewItemsConfig ({data: formItemsConfig, done}) {
        var formItemsConfigs = deepClone(this.formItemsConfigs)
        formItemsConfigs[this.activeName] = formItemsConfig

        this.$store.dispatch('saveAdvSearchConfig', {
          searchType: 'BusinessCardGroup',
          config: formItemsConfigs
        }).then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
      },
      addNewBusiness () {
        this.$router.push({path: '/index/business/newBusiness'})
      },
      /*
      * 快捷搜索时间
      * */
      searchDataReturn (value) {
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let startTime = ''
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        if (value === 'week') {
          // 近一周
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'today') {
          // 今天
          startTime = getFormatDateTime(new Date(mtDate)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'yesterday') {
          // 昨天
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 00:00:00'
          endTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 23:59:59'
        } else if (value === 'month') {
          // 近一月
          startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 29)).split(' ')[0] + ' 00:00:00'
        } else if (value === 'oneYear') {
          let year = nowTime.getFullYear()
          startTime = year + '-01-01 00:00:00'
        } else if (value === 'lastYear') {
          let year = nowTime.getFullYear() - 1
          startTime = year + '-01-01 00:00:00'
          endTime = year + '-12-31 23:59:59'
        } else if (value === 'threeYear') {
          let threeYear = new Date()
          threeYear.setFullYear(nowTime.getFullYear() - 3)
          startTime = getFormatDateTime(threeYear)
        } else {
          endTime = ''
        }
        let searchQuery = {
          createTime$begin: startTime,
          createTime$end: endTime
        }
        return searchQuery
      },
      blank () {
        this.$store.commit('BLANK', this.activeName)
      },
      routeToMe (isbeforeMount) {
        let query = this.$route.query
        if (query.flag === 'advSearch') {
          this.activeName = query.active
          this.$store.commit('BLANK', this.activeName)
          this.search[this.activeName].partakeAgentRemark = false
          let form = this.search[this.activeName].isChildren.adv.form
          for (let key in form) {
            if (key === 'custom') {
              form.custom = {}
            } else if (key === 'flow') {
              form[key] = []
            } else {
              form[key] = null
            }
          }
          this.search[this.activeName].isChildren.adv.form.number = query.busNumber
//          let user = this.$store.state.session.user
          if (query.type === 'attention') {
            // 我关注的工单
            this.search[this.activeName].isChildren.adv.form.searchType = 'myFollowedBusiness__' + this.$t('business.myFollowedBusiness')
          } else if (query.type === 'businessJoin') {
            // 我参与处理的工单
            this.search[this.activeName].isChildren.adv.form.searchType = 'myParticipated__' + this.$t('business.myParticipated')
          }
          this.advSearch(false, 1).then(() => {
            let list = this.$store.state[this.type][this.type + 'List'].list || []
            if (list.length) {
              let data = list[0]
              this.$router.push('/index/business/business_all/' + data._id + '/' + (data.customer || 'no-customer-bus'))
              this.$store.commit('business/REFRESH_BUS_RIGHT', Math.random())
            }
          })
        } else if (query.flag === 'toCard') {
          this.changeTab(query.active)
        } else if (isbeforeMount) {
          this.changeTab(this.activeName, true)
        }
      },
      allCountClear () {
        this.allCount = 0
      },
      getAllCount () {
        this.allCount = 0
//        let form = this.qu
//        form.searchAllCount = true // 此参数是防止vuex的值被改动
        let more = false
        this.$store.dispatch(this.quAction, this.qu).then((res) => {
          if (res.success) {
            this.allCount = res.count
            this.$store.commit('business/SET_BUSSINESS_MORE', {more})
            this.loading = false
          }
        })
      },
      getBusiness (store, tabName, data) {
        this.allCount = 0
        let action = 'queryAllBusiness'
        let sessionId = this.$store.state.session.sessionId
        if (tabName === 'business_my') {
          data.flag = 'kf'
          data.menu = 'my'
          //快捷搜索为多选，这边默认加上的status和master数组处理
          if(data.type){
            data.status = ['dealing']
            data.master = [sessionId]
          }else{
            data.status = 'dealing'
            data.master = sessionId
          }
        } else if (tabName === 'business_all') {
          data.menu = 'all'
          data.flag = 'kf'
        } else {
          data.flag = 'kf'
          data.menu = 'undeal'
          data.master = ''
          //快捷搜索为多选，这边默认加上的status数组处理，master默认空不处理
          if(data.type){
            data.status = ['dealing']
          }else{
            data.status = 'dealing'
          }
        }
        data.followedAgents = ''
        if (data.searchType === 'myFollowedBusiness') {
          data.followedAgents = sessionId
        } else if (data.searchType === 'temp') {
          data.saveFlag = 'temp'
          data.master = sessionId
        }
        // 如果工单参与人是我
        if (data.searchType === 'myParticipated') {
          data.myParticipated = true
//          delete data.menu
        }
        delete data.searchType
        let _qu = deepClone(data)
        _qu.queryCount = true
        this.qu = _qu
        this.quAction = action + 'Count'
        //当快捷查询稍后处理数据时，后端会返回全部数据，前端做数据分页切割
        return store.dispatch(action, data).then((res) => {
          if (res && res.success) {
            if (res.list.length === 0) {
              this.laterProcessData = []
              if (res.more) {
                this.$message.error('页数多余1000，返回第一页！')
                this.turnPage(1)
              } else {
                let page = Math.ceil(res.count / 10)
                if (res.count === 0) {
                  // 第一页且count为0是不再发请求
                  this.search[this.activeName].pagination.currentPage = 1
                  return
                }
                this.turnPage(page)
              }
            }else{
              if(data.laterProcess){
                let maxPage = Math.ceil(res.count / 10)
                if (this.search[this.activeName].pagination.currentPage > maxPage) {
                  this.search[this.activeName].pagination.currentPage = maxPage
                }
                let page = this.search[this.activeName].pagination.currentPage
                this.turnPage(page,true)
              }else{
                this.laterProcessData = []
              }
            }
          }
          return Promise.resolve()
        })
      },
      changeCardItem (index) {
        this.$emit('changeCardItem')
      },
      defaultSetting () {
        // 设置高级搜索默认时间
        let week = this.searchDataReturn('week')
        this.search.business_all.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
      },
      resetAdvSearch () {
        let currentTab = this.search[this.activeName]
        currentTab.pagination.currentPage = 1
        for (let key in currentTab.isChildren.adv.form) {
          if (key !== 'custom') {
            if (key === 'flow') {
              currentTab.isChildren.adv.form[key] = []
            } else {
              currentTab.isChildren.adv.form[key] = null
            }
          } else {
            currentTab.isChildren.adv.form[key] = {}
          }
        }
        this.search[this.activeName].isChildren.adv.advSearchOptions.custom = []
        this.search[this.activeName].isChildren.adv.advSearchOptions.localed.some((item) => {
          console.log(item.name,'ietm')
          if (item.name === 'step') {
            item.data = []
            return false
          }
          if (item.name === 'customField') {
            item.data = []
            return false
          }
          if (item.name === 'textFieldContent') {
            item.disabled = true
            return false
          }
          if (item.name === 'stepHistory') {
            item.data = []
            return true
          }
        })
        if (this.activeName === 'business_all') {
          this.defaultSetting()
        }
      },
      clearSearchQuery () {
        // this.resetAdvSearch()
        this.search[this.activeName].isAdvSearch = false
        this.search[this.activeName].isChildren.nomalForm = deepClone(normalForm)
        // this.search[this.activeName].currentSelect = {value: '', condition: {}}
        this.search[this.activeName].isChildren.adv.badgeList = {}
      },
      changeTab (tabName, noPush) {
        this.pages = 0
        this.$store.commit('business/CLEAR_BUS_LIST')
        this.$store.commit('BLANK', tabName)
        this.allCount = 0
        this.search[this.activeName].partakeAgentRemark = false
        this.activeName = tabName
        addZhuGeTrack(tabName)
        // 清空搜索中的查询条件
        // this.clearSearchQuery()
//        if (this.activeName === 'business_all') {
//          this.handlerQuickSelect(this.search[this.activeName].isChildren.select[4].value)
//        } else {
//          this.handlerQuickSelect(this.search[this.activeName].isChildren.select[0].value)
//        }
        if (this.search[this.activeName].isAdvSearch) {
          this.advSearch()
        } else {
          let current = this.search[this.activeName]
          let select = current.currentSelect.value === undefined ? current.isChildren.defaultSelect : current.currentSelect.value
          this.handlerQuickSelect(select)
        }

        this.$store.dispatch('refreshUndealNum')
        if (!noPush) {
          this.$router.push({ path: '/index/business' })
        }
      },
      turnPage (pageNum,flag) {
        if(flag){
          this.search[this.activeName].pagination.currentPage = pageNum || 1
          let size = 10
          let end = Math.min(size * (pageNum), this.$store.state[this.type][this.type + 'List'].count)
          this.laterProcessData = this.$store.state[this.type][this.type + 'List'].list.slice(size * (pageNum - 1), end)
        }else{
          this.laterProcessData = []
          this.allCount = 0
          if (this.search[this.activeName].isAdvSearch) {
            this.advSearch(false, pageNum)
          } else {
            this.nomalSearch(this.search[this.activeName].isChildren.nomalForm.query, pageNum)
          }
          // 一定要设置为false,这样才代表是翻页,而不是搜索
          this.search.isSearch = false
        }
      },
      handlerSelectChange (selectObj) {
        let selectName = selectObj.selectName
        let selectValue = selectObj.selectValue
        let custom = selectObj.custom
        let cascadeIndex = selectObj.cascadeIndex
        if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'createUser') {
          this.search[this.activeName].isChildren.adv.form.ownercomCreateUser = null
          this.search[this.activeName].isChildren.adv.form.createUser = null
          this.search[this.activeName].isChildren.adv.form.ownerdepCreateUser = null
          if (selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.createUser = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName + 'CreateUser'] = selectValue
          }
        }
        if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'processMember') {
          this.search[this.activeName].isChildren.adv.form.ownercomProcessMember = null
          this.search[this.activeName].isChildren.adv.form.processMember = null
          this.search[this.activeName].isChildren.adv.form.ownerdepProcessMember = null
          if (selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.processMember = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName + 'ProcessMember'] = selectValue
          }
        }
        if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'master') {
          this.search[this.activeName].isChildren.adv.form.ownercom = null
          this.search[this.activeName].isChildren.adv.form.master = null
          this.search[this.activeName].isChildren.adv.form.ownerdep = null
          if (selectName === 'owner') {
            this.search[this.activeName].isChildren.adv.form.master = selectValue
          } else {
            this.search[this.activeName].isChildren.adv.form[selectName] = selectValue
          }
        }
        // 工单类型改变
        if (selectName === 'flow') {
          if (selectValue.length !== 1 || selectValue.length === 0) {
            this.search[this.activeName].isChildren.adv.advSearchOptions.custom = []
            this.search[this.activeName].isChildren.adv.form.custom = {}
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'step') {
                this.search[this.activeName].isChildren.adv.form.step = null
                item.data = []
              }
              if (item.name === 'stepHistory') {
                this.search[this.activeName].isChildren.adv.form.stepHistory = null
                item.data = []
              }
              if (item.name === 'customField') {
                this.search[this.activeName].isChildren.adv.form.customField = null
                item.data = []
              }
              if (item.name === 'textFieldContent') {
                this.search[this.activeName].isChildren.adv.form.textFieldContent = null
                item.disabled = true
              }
            })
            return
          }
          getBusinessFlowStep(this.$store, selectValue.toString()).then((flow) => {
            let steps = flow.steps || []
            let stepsSelectData = []
            let Fields = flow.fields || []
            let FieldsSelectData = [{label: this.$t('public.all'), value: ''}]
            for (let i = 0; i < steps.length; i++) {
              let stepsItem = steps[i]
              stepsSelectData.push({label: stepsItem.name, value: stepsItem._id})
            }
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'step') {
                this.search[this.activeName].isChildren.adv.form.step = null
                item.data = stepsSelectData
              }
              if (item.name === 'stepHistory') {
                this.search[this.activeName].isChildren.adv.form.stepHistory = null
                item.data = stepsSelectData
              }
            })
            for (let i = 0; i < Fields.length; i++) {
              let FieldsItem = Fields[i]
              if(FieldsItem.type=='single'||FieldsItem.type=='multi'){
                FieldsSelectData.push({label: FieldsItem.name, value: FieldsItem._id})
              }
            }
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'customField') {
                this.search[this.activeName].isChildren.adv.form.customField = null
                item.data = FieldsSelectData
              }
            })
            let startStep = getStartStep(flow)
            let step = getFlowStepById(flow, startStep._id)
            let fields = step ? step.stepFields : []
            let flowFields = flow ? flow.fields : []
            let customFormFields = createFlowCustomFields(fields, flowFields, true)
            // let newFieldsArr = []
            // if (customFormFields.advFields) {
            //   customFormFields.advFields.forEach((item) => { // 去掉客户自定义字段中日期
            //     if (item.inputType !== 'time' && item.inputType !== 'datetime' && item.inputType !== 'date') {
            //       newFieldsArr.push(item)
            //     }
            //   })
            // }
            this.search[this.activeName].isChildren.adv.advSearchOptions.custom = customFormFields.advFields || []
            this.search[this.activeName].isChildren.adv.form.custom = customFormFields.customForm
          })
        }
        if(selectName === 'status'&&!this.search[this.activeName].isChildren.adv.form.master){
          if(selectValue.length>0){
            let nameArr =[]
            selectValue.map(val=>{
              nameArr.push(val.split('__')[1])
            })
            //待办和待领取特殊处理，但同时存在masterStatus为''，待领取''.待办null
            let count = 0
            if(nameArr.indexOf(this.$t('business.todo'))!==-1){
              count++
            }
            if(nameArr.indexOf(this.$t('business.undeal'))!==-1){
              count++
            }
            if(count>1){
              this.search[this.activeName].isChildren.adv.form.master = ''
              this.search[this.activeName].isChildren.adv.form.masterStatus=''
            } else{
              if(nameArr.includes(this.$t('business.todo'))){
                this.search[this.activeName].isChildren.adv.form.master = null
                this.search[this.activeName].isChildren.adv.form.masterStatus=null
              }
              if(nameArr.includes(this.$t('business.undeal'))) {
                this.search[this.activeName].isChildren.adv.form.masterStatus = ''
              }
            }
          }
        }
        if(selectName === 'customField'){
          if(selectValue!==''){
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'textFieldContent') {
                this.search[this.activeName].isChildren.adv.form.textFieldContent = null
                item.disabled = false
              }
            })
          }else{
             this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'textFieldContent') {
                this.search[this.activeName].isChildren.adv.form.textFieldContent = null
                item.disabled = true
              }
            })
          }
        }
        // 自定义字段的级联
        if (custom) {
          let fieldId = selectName.split('_')[0]
          let rootValue = this.search[this.activeName].isChildren.adv.form.custom[fieldId]
          addBusienssSelectCascade(this.$store, selectValue, fieldId, cascadeIndex, rootValue).then((labels, cascade) => {
            this.search[this.activeName].isChildren.adv.advSearchOptions.custom.forEach((item) => {
              // let selectName = fieldId + '_' + (cascadeIndex + 1)
              let currentField = item.name.split('_')
              if (currentField[0] === fieldId) {
                // 当前select后面的下拉框重置
                if (currentField[1] > cascadeIndex + 1) {
                  this.search[this.activeName].isChildren.adv.form.custom[item.name] = null
                  item.data = []
                } else if (currentField[1] === (cascadeIndex + 1).toString()) {
                  this.search[this.activeName].isChildren.adv.form.custom[item.name] = null
                  item.data = labels
                }
              }
            })
          })
        }
      },
      refreshCustomSearch () {
        return this.$store.dispatch('queryQuickSearchListAll', {}).then((res) => {
          let obj = {}
          let all = [
            {label: this.$t('public.createTime'), value: 'none', disabled: true, condition: {}},
            {label: this.$t('webchat.today'), value: 'time__today', condition: {}},
            {label: this.$t('webchat.yesterday'), value: 'time__yesterday', condition: {}},
            {label: this.$t('webchat.lastWeek'), value: 'time__week', condition: {}},
            {label: this.$t('webchat.lastMonth'), value: 'time__month', condition: {}},
            {label: this.$t('webchat.oneYear'), value: 'time__oneYear', condition: {}},
            {label: this.$t('webchat.lastYear'), value: 'time__lastYear', condition: {}},
            {label: this.$t('business.weekParticipated'), value: 'time__week__participated', condition: {processMember: this.$store.state.session.sessionId, quickSearch: true}},
            {label: this.$t('business.weekFollowdeAgent'), value: 'time__week__followdeAgent', condition: {searchType: 'myFollowedBusiness', quickSearch: true}},
            {label: this.$t('business.weekCreated'), value: 'time__week__created', condition: {createUser: this.$store.state.session.sessionId, quickSearch: true}}
          ]
          if (this.$store.state.iframeMessage.showBusinessCreateTime) {
            all.splice(7, 0, {label: this.$t('webchat.threeYear'), value: 'time__threeYear', condition: {}})
          }
          let businessType = this.$store.state.business.transCache.businessTypes
          let undeal = [
            {label: this.$t('public.all'), value: '', condition: {flow: ''}},
            ...businessType
          ]
          let my = [
            {label: this.$t('public.all'), value: '', condition: {flow: ''}},
            {label: this.$t('business.laterProcess'), value: 'laterProcess', condition: {laterProcess: true}},
            {label: this.$t('business.myTemp'), value: 'temp', condition: {saveFlag: 'temp'}},
            {label: this.$t('business.backBusiness'), value: 'isBack', condition: {isBack:true}, sortClass: 'sortClass'},

            ...businessType
          ]
          let selectObj = {all: '', my: '', undeal: ''}
          obj = {undeal, my, all}
          if (res.success) {
            let list = res.data || []
            list.forEach((item) => {
              if(item.type){
                item.condition.customSearch = 'customSearch'
                item.condition.type = item.type
              }
              obj[item.menu].push({label: item.name, value: item._id, condition: item.condition})
              selectObj[item.menu] = (selectObj[item.menu] === '' && item.default === 'true') ? item._id : selectObj[item.menu]
            })
          }
          this.search.business_undeal.isChildren.defaultSelect = selectObj.undeal || ''
          this.search.business_my.isChildren.defaultSelect = selectObj.my || ''
          this.search.business_all.isChildren.defaultSelect = selectObj.all || 'time__week'
          this.search.business_undeal.isChildren.select = obj.undeal
          this.search.business_my.isChildren.select = obj.my
          this.search.business_all.isChildren.select = obj.all
          let flag = this.search[this.activeName].isChildren.select.some((item) => {
            if (this.search[this.activeName].currentSelect.value === item.value) {
              return true
            }
          })
          // 如果当前快捷搜索条件为其中一个自定义快捷搜索是，刷新列表
          if (!flag && this.search[this.activeName].currentSelect.value) {
            this.changeTab(this.activeName, true)
          }
        })
      },
      advSearch (clearBadge, pageNum, emitData) {
        window._hmt && window._hmt.push(['_trackEvent', '其他统计', this.activeName + ' 高级搜索'])
        this.allCount = 0
//        let selectName = ''
//        if (emitData && emitData.selectName) {
//          selectName = emitData.selectName ? emitData.selectName : ''
//        }
        this.noChange = true
//        if (selectName === 'flow') {
//          this.search[this.activeName].isChildren.nomalForm.value = ''
//        }
        this.search[this.activeName].currentSelect.value = ''
        this.search[this.activeName].currentSelect.condition = {}
        this.search.isSearch = true
        let self = this
        self.loading = true
        let form = this.search[this.activeName].isChildren.adv.form
        if(this.activeName=='business_all'&&form.status){
          form.status.forEach(item=>{
            if(item.split('__')[1]== this.$t('business.undeal')){
                form.master = ''
            }
          })
        }
        let tempArr = {}
        // 全部tab下工单编号为空时，创建时间必填
        if (this.activeName === 'business_all' && !form.number && (!form.createTime)) {
          this.defaultSetting()
        }
        // deepClone后createtiem里日期消失
        if (form.createTime && form.createTime[0] !== null) {
          form.createTime$begin = getDateTime(form.createTime[0])
        } else {
          form.createTime$begin = ''
        }
        if (form.createTime && form.createTime[1] !== null) {
          form.createTime$end = getDateTime(form.createTime[1])
        } else {
          form.createTime$end = ''
        }
        if (form.processEndTime && form.processEndTime[0] !== null) {
          form.processEndTime$begin = getDateTime(form.processEndTime[0])
        } else {
          form.processEndTime$begin = ''
        }
        if (form.processEndTime && form.processEndTime[1] !== null) {
          form.processEndTime$end = getDateTime(form.processEndTime[1])
        } else {
          form.processEndTime$end = ''
        }
        for (let m in form.custom) {
          if (form.custom[m] instanceof Date) {
            form.custom[m] = getDateTime(form.custom[m])
          }
        }
        let searchQuery = deepClone(form)
        let flows = this.$store.state.business.transCache.businessTypes
        if (clearBadge === true) {
          self.search[this.activeName].isAdvSearch = false
          // 清空高级搜索选项
          this.resetAdvSearch()
          searchQuery = {}
        } else {
          self.search[this.activeName].isAdvSearch = true
          let custom = searchQuery.custom
          delete searchQuery.createTime
          delete searchQuery.processEndTime
          
          for (let key in searchQuery) { // 搜索条件回显处理
            if ((searchQuery[key] || searchQuery[key] === false) && key !== 'custom') {
              tempArr[key] = searchQuery[key]
              if (key === 'flow') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                  for (let i = 0; i < flows.length; i++) {
                    if (flows[i].value === searchQuery[key][m]) {
                      name += flows[i].label + ' '
                      break
                    }
                  }
                }
                tempArr[key] = name
              } else if (key === 'priority') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {

                    name += searchQuery[key][m].split('__')[1] + ' '
                    if(searchQuery[key][m].split('__')[1]==this.$t('business.priority1')){
                      searchQuery[key][m]=searchQuery[key][m].split('__')[0]
                    }else if(searchQuery[key][m].split('__')[1]=='!'+this.$t('business.priority2')){
                      searchQuery[key][m]=searchQuery[key][m].split('__')[0]
                    }else{
                      searchQuery[key][m]=searchQuery[key][m].split('__')[0]
                    }
                }
                tempArr[key] = name
              } else if (key === 'step') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                  name += getFlowStepNameByCache(searchQuery.flow.toString(), searchQuery[key][m]) + ' '
                }
                tempArr[key] = name
              } else if (key === 'stepHistory') {
                let name = ''
                for (let m = 0; m < searchQuery[key].length; m++) {
                  name += getFlowStepNameByCache(searchQuery.flow.toString(), searchQuery[key][m]) + ' '
                }
                tempArr[key] = name
              } else if (key === 'status') {
                let statusArr = []
                tempArr[key] = []
                for (let m = 0; m < searchQuery[key].length; m++) {
                  if (searchQuery[key][m].indexOf('__')!==-1) {
                    tempArr[key] += searchQuery[key][m].split('__')[1] + ' '
                    statusArr.push(searchQuery[key][m].split('__')[0])
                  } else {
                    tempArr[key] += searchQuery[key][m]
                  }
                }
                searchQuery[key] = statusArr
              }else if (key === 'customField') {
                tempArr[key] = getTextFieldsNameByCache(searchQuery.flow.toString(), searchQuery.customField)
              }else if (key === 'processTimeout') {
                if (tempArr[key] === true) {
                  tempArr[key] = this.$t('business.totalTimeStateUncomplete2')
                } else if (tempArr[key] === false) {
                  tempArr[key] = this.$t('business.noTimeout')
                } else {
                  tempArr[key] = ''
                }
              } else if (key === 'existAttach') {
                if (tempArr[key] === true) {
                  tempArr[key] = this.$t('business.attachment')
                } else if (tempArr[key] === false) {
                  tempArr[key] = this.$t('business.noAttachment')
                } else {
                  tempArr[key] = ''
                }
              } else if (key === 'createMode') {
                let str = ''
                let arr = []
                searchQuery[key].forEach(item=>{
                  if (item.match(/__/)) {
                    str += item.substr(item.indexOf('__') + 2) + ' '
                    arr.push(item.substr(0, item.indexOf('__'))) 
                  } else {
                    str += item
                  }
                })
                tempArr[key] = str
                searchQuery[key] = arr
              }else if (searchQuery[key] && typeof searchQuery[key] === 'string') {
                if (searchQuery[key].match(/__/)) {
                  tempArr[key] = searchQuery[key].substr(searchQuery[key].indexOf('__') + 2)
                  searchQuery[key] = searchQuery[key].substr(0, searchQuery[key].indexOf('__'))
                } else {
                  tempArr[key] = searchQuery[key]
                }
              }
            }
          }
          for (let i in custom) {
            searchQuery[i] = custom[i]
            // 处理time和date数据
            if (custom[i]) {
              this.search[this.activeName].isChildren.adv.advSearchOptions.custom.forEach((item) => {
                if (item.name === i && item.inputType === 'time') {
                  searchQuery[i] = custom[i].split(' ')[1]
                } else if (item.name === i && item.inputType === 'date') {
                  searchQuery[i] = custom[i].split(' ')[0]
                }
              })
            }
          }
          // 自定义字段回显
          tempArr = Object.assign(tempArr, advancedSearchBack(custom))
          delete searchQuery.custom
        }
        // 我参与的工单提示
        if (!searchQuery.processMember) {
          this.search[this.activeName].partakeAgentRemark = false
        } else {
          this.search[this.activeName].partakeAgentRemark = true
        }
        // 部门组件处理
        if (searchQuery.ownercom === 'all') {
          searchQuery.ownercom = ''
        }
        if (searchQuery.ownercomCreateUser === 'all') {
          searchQuery.ownercomCreateUser = ''
        }
        if (searchQuery.ownercomProcessMember === 'all') {
          searchQuery.ownercomProcessMember = ''
        }
        this.search[this.activeName].isChildren.adv.badgeList = removeEmptyProperty(tempArr);
        searchQuery.page = pageNum || 1
        let morePage = 1
        morePage = searchQuery.page === 1 ? 1 : Math.floor(pageNum / this.pages + 1)
        searchQuery.morePage = morePage || 1
        self.search[self.activeName].pagination.currentPage = pageNum || 1
        self.search[self.activeName].condition = searchQuery
        // console.log(searchQuery,'searchQuery')
        if(searchQuery.customField && searchQuery.textFieldContent){
          let obj = {}
          obj[searchQuery.customField] = searchQuery.textFieldContent
          searchQuery.customField=obj
        }else{
          searchQuery.customField=null
        }
        delete searchQuery.textFieldContent
        return this.getBusiness(this.$store, this.activeName, searchQuery).then(() => {
          if (searchQuery.page === 1) {
            this.pages = this.count / 10
          }
          self.loading = false
          this.noChange = false
          return Promise.resolve()
        })
      },
      /**
       * 快捷搜索
       */
      handlerQuickSelect (value) {
        this.search[this.activeName].currentSelect.value = value
        this.search[this.activeName].isChildren.select.some((item) => {
          if (item.value === value) {
            if(item.condition&&item.condition.stepFlow){
              delete item.condition.stepFlow
            }
            this.search[this.activeName].currentSelect.condition = deepClone(item.condition)
            return true
          }
        })
        let type = value.split('__')
        if (value === 'time__oneYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-今年'])
        } else if (value === 'time__lastYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-去年'])
        } else if (value === 'time__threeYear') {
          window._hmt && window._hmt.push(['_trackEvent', '其他统计', '工单查询-近三年'])
        }
        if (type[0] === 'time') {
          let time = this.searchDataReturn(type[1])
          utilExtend(this.search[this.activeName].currentSelect.condition, time)
          // let start = time.createTime$begin || ''
          // let end = time.createTime$end || ''
          // if (start && end) {
          //   this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [new Date(time.createTime$begin), new Date(time.createTime$end)])
          // } else {
          //   this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [])
          // }
        } else {
          // this.$set(this.search[this.activeName].isChildren.adv.form, 'createTime', [])
        }
        this.search[this.activeName].partakeAgentRemark = false
        if (this.search[this.activeName].isAdvSearch && value === null) {
          return
        }
        this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
        this.search[this.activeName].isAdvSearch = false
        this.search.isSearch = true
        let self = this
        self.loading = true
        let queryData = deepClone(this.search[self.activeName].isChildren.nomalForm)
        Object.assign(queryData, this.search[this.activeName].currentSelect.condition)
        self.search[self.activeName].pagination.currentPage = 1
        queryData.morePage = 1
        queryData.page = 1
        this.getBusiness(this.$store, self.activeName, queryData).then(() => {
          if (queryData.page === 1) {
            this.pages = this.count / 10
          }
          self.loading = false
        })
      },
      nomalSearch (value, pageNum) {
        this.allCount = 0
        this.search[this.activeName].partakeAgentRemark = false
        this.search.isSearch = true
        let self = this
        self.loading = true

        this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
        this.search[this.activeName].isAdvSearch = false

        this.search[self.activeName].isChildren.nomalForm.query = value
        let queryData = deepClone(this.search[self.activeName].isChildren.nomalForm)
        Object.assign(queryData, this.search[this.activeName].currentSelect.condition)
        queryData.page = pageNum || 1
        self.search[self.activeName].pagination.currentPage = pageNum || 1
        let morePage = 1
        morePage = queryData.page === 1 ? 1 : Math.floor(pageNum / this.pages + 1)
        queryData.morePage = morePage || 1
        this.getBusiness(this.$store, this.activeName, queryData).then(() => {
          if (queryData.page === 1) {
            this.pages = this.count / 10
          }
          self.loading = false
        })
      },
      handleRefresh () {
        this.$store.dispatch('refreshUndealNum')
        let _page = this.search[this.activeName].pagination.currentPage
        this.turnPage(_page)
        // if (this.search[this.activeName].isAdvSearch) {
        //   this.advSearch()
        // } else {
        //   this.nomalSearch(this.search[this.activeName].isChildren.nomalForm.query)
        // }
      },
      plus (path) {
        this.$router.push({path})
      },
      removeBadge () {
        // 移除bandage后，快捷搜索
        this.search[this.activeName].partakeAgentRemark = false
        this.search[this.activeName].currentSelect = {value: '', condition: {}}
        this.resetAdvSearch()
        let current = this.search[this.activeName]
        let select = current.currentSelect.value = current.isChildren.defaultSelect || ''
        this.handlerQuickSelect(select)
        this.clearChecked = Math.random()
      },
      ifRemark (data) {
        // this.allCount = 0
        this.search[this.activeName].partakeAgentRemark = data
      },
      updateGuidanceSuccess (type) {
        if (type === 'click') {
          this.getNoviceKeyStatus = {'businessViewSwitch': true}  
        } else {
          let guidance = this.$getCache('guidance')
          this.getNoviceKeyStatus = guidance || {'businessViewSwitch': true}
        }
      }
    },
    components: {
      BusinessCard,
      Search,
      'v-select': Select,
      CardGroupSolt,
      InputSearch,
      AdvancedSearch,
      Pagination,
      Refresh,
      AdvSchBadge,
      popoverNovice
    },
    mounted() {
      if(this.shortcutOpen) {
        document.addEventListener('keydown', this.shortcutDispatch)
      }
    },
    beforeDestroy () {
      document.removeEventListener('keydown', this.shortcutDispatch)
    }
  }
  function getBusinessFlowStep (store, flowId) {
    return store.dispatch('getCache', {type: 'businessFlow', id: flowId})
  }
  function getBusinessFlow (store) {
    return store.dispatch('getBusinessFlow')
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .icon-qiehuanshitu
    font-size 18px
  .el-icon--right
    color $c-main
  .rel-operation
    :hover
      color $c-main !important
</style>
